import messageBoxEl from "./index.vue"
import {createApp } from "vue"
import mitt from "../../mitt"
const typeArr = ["alert",'confirm','prompt']

const hideMessageBox = (app,vm) => {
  app.unmount()
}

const showMessageBox = (app) => {
  return new Promise((resolve,reject)=>{
    const fragment = document.createDocumentFragment()
    const vm = app.mount(fragment)
    document.body.appendChild(fragment)

    vm.setVisible(true)

    //监听确认按钮事件
    mitt.on("messageBoxConfirm",(res)=>{
      resolve(res)
      hideMessageBox(app,vm)
    })
    //监听取消按钮事件
    mitt.on("messageBoxCacel",()=>{
      reject()
      hideMessageBox(app,vm)
    })
  })
}


const messageBox = (options) => {
  const app = createApp(messageBoxEl , options)
  return showMessageBox(app)
}


typeArr.forEach(ele => {
  messageBox[ele] = (options) => {
    options.type = ele
    if(ele === "prompt") options.showCacelButton = options.showCacelButton ?? true
    return messageBox(options)
  }
})


export default messageBox